package com.sp.service.impl;

import com.sp.constant.EmployeeMessageConstant;
import com.sp.mapper.EmployeeRoleMapper;
import com.sp.model.entity.Employee;
import com.sp.model.entity.EmployeeDetails;
import com.sp.model.entity.EmployeeRole;
import com.sp.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tong
 * @date 2024/4/11 21:47
 */
@Service
public class EmployeeDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeRoleMapper employeeRoleMapper;

    /**
     * 管理员登录与授权
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Employee employee = employeeService.selectByUsername(username);
        if (employee == null) {
            throw new UsernameNotFoundException(EmployeeMessageConstant.ACCOUNT_NOT_FOUND);
        }

        List<EmployeeRole> employeeRoles = employeeRoleMapper.selectByEmployeeId(employee.getId());

        EmployeeDetails employeeDetails = new EmployeeDetails();
        employeeDetails.setEmployee(employee);
        employeeDetails.setEmployeeRoles(employeeRoles);
        return employeeDetails;
    }

}